package edu.ptu.zhiyan.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.ptu.zhiyan.base.Result;
import edu.ptu.zhiyan.entity.Question;
import edu.ptu.zhiyan.service.question.impl.QuestionServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author shengxiao
 * @date 2021/5/21 23:27
 */
@RestController
//@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/api/question")
public class QuestionController {

    @Resource
    private QuestionServiceImpl questionServiceImpl ;

    // 添加问题
    @PostMapping("/add")
    public Result saveQuestion(@RequestBody Question question){
        //question.setTimestamp(new Date());
        if(questionServiceImpl.addQuestion(question)){
            return Result.ok("添加问题成功") ;
        }else{
            return Result.fail("添加问题失败") ;
        }

    }

    // 查询粗略问题信息，即问题列表
    @GetMapping("/list")
    public Result showQuestionList(){
        List<QuestionServiceImpl.QuestionInfo> questionList = questionServiceImpl.queryQuestion() ;
        if(questionList == null || questionList.size() == 0){
            return Result.fail("查询粗略问题列表失败") ;
        }else{
            return Result.ok(questionList, "查询粗略问题列表成功") ;
        }
    }

    /*// 查询指定问题的详细信息
    @GetMapping("/lista")
    public Result showQuestionList(@RequestParam("uid") Integer uid){
        List<QuestionServiceImpl.QuestionInfo> questionList = questionServiceImpl.queryQuestion() ;
        if(questionList == null || questionList.size() == 0){
            return Result.fail("查询粗略问题列表失败") ;
        }else{
            return Result.ok(questionList, "查询粗略问题列表成功") ;
        }
    }*/


    // 查询问题详细信息
    @GetMapping("/info")
    public Result showQuestion(@RequestParam("qid") Integer qid){
        QuestionServiceImpl.QuestionInfo questionDetail = questionServiceImpl.queryDetailQuestion(qid) ;
        if(questionDetail == null){
            return Result.fail("查询详细问题信息失败") ;
        }else{
            return Result.ok(questionDetail, "查询详细问题信息成功") ;
        }
    }

    @PostMapping("/delete")
    public Result deleteQuestion(@RequestBody JSONObject param){    // 要理解json对象接收参数的妙处
        if(questionServiceImpl.removeQuestion(param.getIntValue("qid"),param.getIntValue("uid"))){
            return Result.ok("删除问题成功") ;
        }else{
            return Result.fail("删除问题失败") ;
        }
    }

    // 通过用户id获取其具体信息（此接口待定，先不编写）
    /*@GetMapping("/user/info")
    public Result showQuestionById(@RequestParam())*/
}
